/*
 * @Author: your name
 * @Date: 2021-09-12 11:33:11
 * @LastEditTime: 2022-06-16 19:14:50
 * @LastEditors: 夏郑兴 971348024@qq.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /gitee-project/whale-admin-web/src/utils/system/request.ts
 */
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'
import store from '@/store'
import { ElMessage } from 'element-plus'
const baseURL: any = import.meta.env.VITE_BASE_URL

const service: AxiosInstance = axios.create({
  baseURL: baseURL,
  timeout: 1800000,
  // 'Content-Type': 'application/json'
})
// service.defaults.timeout = 18000*1000
// 请求前的统一处理
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // JWT鉴权处理
    if (store.getters['user/token']) {
      config.headers['Authorization'] = 'Bearer ' + localStorage.getItem("Auth")
      config.headers['Accept-Version'] = '1.0.0'
    }
    return config
  },
  (error: AxiosError) => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data
    if (res.code === 200) {
      return res
    } else {
      showError(res)
      return Promise.reject(res)
    }
  },
  (error: AxiosError) => {
    console.log(error) // for debug
    const badMessage: any = error.message || error
    const code = parseInt(badMessage.toString().replace('Error: Request failed with status code ', ''))
    // if (code === 403 || code === 401) {
    showError({ code, message: badMessage })
    // }
    return Promise.reject(error)
  }
)

// 错误处理
function showError(error: any) {
  // token过期，清除本地数据，并跳转至登录页面
  if (error.code === 403 || error.code === 401) {
    ElMessage.error('登录状态已失效，请重新登录！')
    localStorage.clear()
    sessionStorage.clear()
    // to re-login
    setTimeout(() => {
      store.dispatch('user/loginOut')
    }, 1000);
  } else {
    ElMessage({
      message: error.msg || error.message || '服务异常',
      type: 'error',
      duration: 3 * 1000
    })
  }

}

export default service